import { MAINROUTE } from '../../interface/micro.interface';

// 存取全部的路由
let MAINROUTE = {};

/**针对路由配置增加写api */
export function setMAINROUTE(mainroute: MAINROUTE[]) {
  MAINROUTE = loopMAINROUTEDATA(mainroute);
}

/** 子应用构造自己的路由结构-angular - 每次都要用新的class，所以不能做缓存 */
export function getNgRoute(key: string, data, moduleName?: string) {
  const modulename = moduleName ?? '__main';
  if (!MAINROUTE[key] || !MAINROUTE[key].hasOwnProperty(modulename)) {
    throw `应用未配置${modulename === '__main' ? '此应用' : `${modulename}`}的路由，无法加载，或者不使用此函数`;
  }
  console.log('0000获取的路由配置',  getNgRouter(MAINROUTE[key][modulename], data))
  return getNgRouter(MAINROUTE[key][modulename], data);
}

const dataMap = {};
// 主应用使用-递归将路由拆解
export function loopMAINROUTEDATA(datas, lastItem?: MAINROUTE, lastPath?: string, childrens?: MAINROUTE[], moduleKey?: 'string') {
  const modulekey = moduleKey ? moduleKey : '__main';
  datas.forEach(data => {
    if (!data.project && !lastItem) {
      throw '路由配置文件错误';
    }
    if (!data.project) {
      data.project = lastItem.project;
    }
    if (!data.page && data.component && data.component.length) {
      data.page = '__empty';
      data.component.forEach(dc => {
        judgeMap(dc.project, dataMap);
        dataMap[dc.project][modulekey].push({
          ...dc,
          path: pathAdd(lastPath, dc.path),
        });
      });
    }
    judgeMap(data.project, dataMap);
    const allPath = pathAdd(lastPath, data.path);
    const setData = {
      ...data,
      allPath,
      childrens: [],
    };
    if (!childrens) {
      dataMap[data.project][modulekey].push(setData);
    } else {
      childrens.push(setData);
    }

    if (data.childrens && data.childrens.length) {
      if (data.module) {
        dataMap[data.project][data.module] = [];
        // 走生成子路由的逻辑
        loopMAINROUTEDATA(data.childrens, data, allPath, null, data.module);
        return;
      }
      loopMAINROUTEDATA(data.childrens, data, allPath, setData.childrens);
    }
  });

  if (childrens) {
    childrens.push({
      path: '**',
      page: '__empty',
    });
  }
  if (!childrens) {
    Object.keys(dataMap).forEach((v: any) => {
      let arr = dataMap[v][modulekey];
      if (arr && Array.isArray(arr)) {
        arr.push({
          path: '**',
          page: '__empty',
        });
      } else {
        arr = [
          {
            path: '**',
            page: '__empty',
          },
        ];
      }
    });
  }

  return dataMap;
}

function judgeMap(project, map) {
  if (!map[project]) {
    map[project] = { __main: [] };
  }
}

function pathAdd(lastPath, path) {
  if (!path) {
    return lastPath;
  }
  lastPath = lastPath ?? '';
  if (path.startsWith('/') || lastPath.endsWith('/')) {
    return lastPath + path;
  } else {
    return lastPath + '/' + path;
  }
}

// 递归写入ng路由
function getNgRouter(structure: MAINROUTE[], data, _childrens?: any[]) {
  // 根据 path直接写入， data是一个map， 直接使用page/module即可，存在childrens 可以没有page 或者module,
  // 每个childrens下面增加一个空组件
  let returnRouter = [];
  let isLoadingModule = false;

  structure.forEach((route: MAINROUTE) => {
    if (!route.hasOwnProperty('path')) {
      console.error(route, `配置错误，必需要path配置`);
      throw '';
    }

    const singleData: any = { path: route.path, data: {} };
    if (route.page && route.module) {
      console.error(`不允许page及module都配置:`, route);
      throw '';
    }
    if (route.page) {
      if (!data[route.page]) {
        console.error(`子应用未配置${route.page}为key的页面，请检查:`, route, '-', data);
        throw '';
      }
      singleData.component = data[route.page];
    }
    if (route.module) {
      if (location.pathname.startsWith(route.allPath)) {
        isLoadingModule = true;
        singleData.loadChildren = data[route.module];
        singleData.data._isShow = true;
      } else {
        singleData.component = data['__empty'];
        singleData.data.__romove = true;
      }
    }

    if (_childrens) {
      _childrens.push(singleData);
    } else {
      returnRouter.push(singleData);
    }

    if (route.childrens && route.childrens.length) {
      singleData.children = [];
      getNgRouter(route.childrens, data, singleData.children);
    }
  });
  if (isLoadingModule) {
    if (_childrens) {
      changeEmpty(_childrens, data);
    } else {
      changeEmpty(returnRouter, data);
    }
  }
  return returnRouter;
}

// 将一些不想跳转的页面修改为空组件
function changeEmpty(arr, data) {
  arr.forEach(v => {
    if (v.data._isShow) {
      return;
    }
    v.component = data['__empty'];
  });
}
